import json
import threading

from geventwebsocket import WebSocketServer, WebSocketApplication, Resource
from core import coreData

data = None
cont=0
class EchoApplication(WebSocketApplication):
    def on_open(self):
        global data
        global cont
        if not data:
            data = coreData.DataSource()
            data.start()
            #t2=threading.Thread(target=self.data.run(), name='threading2')
        cont =cont+1
        print('目前连接人数：%d'% cont)

    def on_message(self, message):
        if '666'==str(message):
            self.ws.send(json.dumps(data, default=data_Dict))


    def on_close(self, reason):
        global cont
        cont=cont-1
        print('断开连接，当前人数 %d'% cont)

def data_Dict(dataObj):
    num,dst1,dst2,dst3,si,cid=dataObj.getData()
    return {'num':num,'mac':dst1+':'+dst2+':'+dst3,'si':si,'cid':cid}



def run(host='127.0.0.1',port=9000):
    """
    :param host: Host
    :param port:端口
    :return:NONE
    默认127.0.0.1:9000
    """
    WebSocketServer(
        (host, port),
        Resource({'/': EchoApplication})
    ).serve_forever()

